#!/Users/martin/.pyenv/shims/python3
import requests
import json
import sys
import base64
import re
import configparser
import urllib3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

#disable InsecureWarning
urllib3.disable_warnings()

#read config.ini
configins = configparser.ConfigParser()
configins.read('config.ini')

#read netconf
ipaddr = configins['netconf']['ipaddr']
serverport = configins['netconf']['serverport']

#base dict set
requestdata = {}
requestdata['userID'] = configins['baseinfo']['userID']
requestdata['userPassword'] = configins['baseinfo']['userPassword']

#other func dict set
requestdata['productBusinessType'] = configins['getProductInfo']['productBusinessType']

#api url set
apiurldata = {}
apiurldata['get_public_key'] = 'https://' + ipaddr + ':' + serverport + '/cap_api/get_public_key'
apiurldata['getDepartment'] = 'https://' + ipaddr + ':' + serverport + '/cap_api/getDepartment'
apiurldata['getProductInfo'] = 'https://' + ipaddr + ':' + serverport + '/cap_api/getProductInfo'
apiurldata['qryEnummetaData'] = 'https://' + ipaddr + ':' + serverport + '/cap_api/qryEnummetaData'


#open session for api
mainsession = requests.session()


#regex set
mesgmatchstr = '.*?maxMessageNo.*?([0-9]+)'
mesgre = re.compile(mesgmatchstr)

def passwdencrypt(pwstr, publickey):
	pwstr = pwstr.encode('utf-8')
	keyPub = RSA.import_key(base64.b64decode(publickey))
	cipher = Cipher_pkcs1_v1_5.new(keyPub)
	encryptpwd = base64.b64encode(cipher.encrypt(pwstr))
	return encryptpwd.decode('utf-8')

def getmaxmesgno(requestdata):
	rqdata = {}
	rqdata['userID'] = requestdata['userID']
	rqdata['commType'] = 'get_public_key'
	rqdata['messageNo'] = '1'
	rc = mainsession.post(url=apiurldata['get_public_key'], json=rqdata, verify=False)
	rcdict = json.loads(rc.text)
	if(rcdict['errorNo'] == 0):
		print('get max mesgno ok, today first login, maxmsgno: 1')
		return 1
	elif('errorInfo' in rcdict.keys()):
		errormsg = rcdict['errorInfo']
		catchgroup = re.search(mesgre, errormsg)
		maxno = int(catchgroup.groups()[0]) + 1
		print('get max mesgno ok, maxmsgno: ', catchgroup.groups()[0])
		return maxno
	else:
		print('get max mesgno failed, please check error detail:')
		print(rc.text)
		return -1

def get_public_key(requestdata):
	global mesgcount
	rqdata = {}
	rqdata['userID'] = requestdata['userID']
	rqdata['commType'] = 'get_public_key'
	requestdata['messageNo'] = requestdata['messageNo'] + 1
	rqdata['messageNo'] = requestdata['messageNo']
	rc = mainsession.post(url=apiurldata['get_public_key'], json=rqdata, verify=False)	
	rcdict = json.loads(rc.text)
	if(rcdict['errorNo'] == 0):
		print('get public key success!')
		publickey = rcdict['data']['publicKey']	
		return publickey
	else:
		print('get public key failed! please check detail:')
		print(rc.text)
		return 233

def getDepartment(requestdata):
	rqdata = {}
	rqdata['userID'] = requestdata['userID']
	rqdata['userPassword'] = requestdata['userPassword']
	rqdata['commType'] = 'getDepartment'
	requestdata['messageNo'] = requestdata['messageNo'] + 1
	rqdata['messageNo'] = requestdata['messageNo']
	rc = mainsession.post(url=apiurldata['getDepartment'], json=rqdata, verify=False)	
	rcdict = json.loads(rc.text)
	if(rcdict['errorNo'] == 0):
		print('getDepartment success!')
		print(rc.text)
		return 0
	else:
		print('getDepartment failed! please check detail:')
		print(rc.text)
		return 233

def getProductInfo(requestdata):
	rqdata = {}
	rqdata['userID'] = requestdata['userID']
	rqdata['userPassword'] = requestdata['userPassword']
	rqdata['commType'] = 'getProductInfo'
	requestdata['messageNo'] = requestdata['messageNo'] + 1
	rqdata['messageNo'] = requestdata['messageNo']
	rqdata['productBusinessType'] = requestdata['productBusinessType']
	rc = mainsession.post(url=apiurldata['getProductInfo'], json=rqdata, verify=False)	
	rcdict = json.loads(rc.text)
	if(rcdict['errorNo'] == 0):
		print('getProductInfo success!')
		print(rc.text)
		return 0
	else:
		print('getProductInfo failed! please check detail:')
		print(rc.text)
		return 233


def qryEnummetaData(requestdata):
	rqdata = {}
	rqdata['userID'] = requestdata['userID']
	rqdata['userPassword'] = requestdata['userPassword']
	rqdata['commType'] = 'qryEnummetaData'
	requestdata['messageNo'] = requestdata['messageNo'] + 1
	rqdata['messageNo'] = requestdata['messageNo']
	rc = mainsession.post(url=apiurldata['qryEnummetaData'], json=rqdata, verify=False)	
	rcdict = json.loads(rc.text)
	if(rcdict['errorNo'] == 0):
		print('qryEnummetaData success!')
		print(rc.text)
		return 0
	else:
		print('qryEnummetaData failed! please check detail:')
		print(rc.text)
		return 233


if(__name__ == '__main__'):
	requestdata['messageNo'] = getmaxmesgno(requestdata)
	publickey = get_public_key(requestdata)
	requestdata['userPassword'] = passwdencrypt(requestdata['userPassword'], publickey)

	#start read actionlist
	actionlist = []
	with open('actionlist.ini', 'r') as f:
		for singleaction in f:
			actionlist.append(singleaction.strip('\n'))
		f.close()

	for singleaction in actionlist:
		exec('rc = %s(requestdata)' % (singleaction))
		input()

mainsession.close()
